查询

Throwable::getMessage()函数—用法及示例

「 获取抛出异常的错误消息 」


函数名称:Throwable::getMessage()

适用版本:PHP 7.0.0 及以上版本

函数描述:Throwable::getMessage() 函数用于获取抛出异常的错误消息。

用法:

  1. 基本用法:
try {
    // 抛出一个异常
    throw new Exception("这是一个异常信息");
} catch (Throwable $e) {
    // 获取异常消息
    $message = $e->getMessage();
    echo "异常消息:$message";
}

输出结果:

异常消息:这是一个异常信息
  1. 在自定义异常类中使用:
class CustomException extends Exception {
    public function __construct($message, $code = 0, Throwable $previous = null) {
        parent::__construct($message, $code, $previous);
    }
    
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}

try {
    // 抛出一个自定义异常
    throw new CustomException("这是一个自定义异常", 42);
} catch (Throwable $e) {
    // 获取异常消息
    $message = $e->getMessage();
    echo "异常消息:$message";
}

输出结果:

异常消息:这是一个自定义异常

注意事项:

  • Throwable::getMessage() 函数只能在异常处理过程中使用,用于获取异常的错误消息。
  • 在 PHP 7.0.0 之前的版本中,可以使用 Exception::getMessage() 函数来获取异常消息。在 PHP 7.0.0 及以上版本中,Exception 类实现了 Throwable 接口,因此 Throwable::getMessage() 可以用于获取异常消息。
补充纠错
上一个函数: Throwable::getPrevious()函数
下一个函数: Throwable::getLine()函数
热门PHP函数
分享链接